package com.ease.kernel.impls.adapter
{
	import com.ease.kernel.Kernel;
	import com.ease.kernel.adapter.IAdapterFactory;
	import com.ease.kernel.adapter.IAdapterManager;
	
	import flash.utils.getQualifiedClassName;
	
	import mx.collections.ArrayCollection;
	
	public final class AdapterManager implements IAdapterManager
	{
		private static var _INSTANCE : AdapterManager;
		
		private static var KERNEL : Kernel;
		
		public function AdapterManager(pri:Private)
		{
			KERNEL = Kernel.getInstance(IAdapterFactory);
		}

		public static function get INSTANCE():AdapterManager{
			if(_INSTANCE == null){
				_INSTANCE = new AdapterManager(new Private());
			}
			return _INSTANCE;
		}
		
		public function getAdapterByClass(adaptable:Object, adapterType:Class):Object
		{
			var factory:IAdapterFactory = findService(adaptable,getQualifiedClassName(adapterType));
			var result:Object = null;
			if(factory != null && adapterType != null){
				result = factory.getAdapter(adaptable, adapterType);
			}
			if (result == null && adaptable is adapterType)
				return adaptable;
			return result;
		}
		
		public function getAdapter(adaptable:Object, adapterTypeName:String):Object
		{
			var factory:IAdapterFactory = findService(adaptable,adapterTypeName);
			var result:Object = null;
			if(factory != null){
				var clazz:Class = findServiceClass(factory,adapterTypeName);
				if (clazz != null)
					result = factory.getAdapter(adaptable, clazz);
				if(result == null && adaptable is clazz)
					result = adaptable;
			}
			if (result == null && getQualifiedClassName(adaptable) == adapterTypeName)
				return adaptable;
			return result;
		}
		
		public function hasAdapter(adaptable:Object, adapterTypeName:String):Boolean
		{
			return findService(adaptable,adapterTypeName) != null;
		}
		
		private function findService(adaptable:Object, adapterTypeName:String):IAdapterFactory{
			var list:ArrayCollection = KERNEL.getServices(adaptable);
			for each(var value:Object in list)
			{
				if(value is IAdapterFactory)
				{
					var factory:IAdapterFactory = value as IAdapterFactory;
					if(findServiceClass(factory,adapterTypeName) != null){
						return factory;
					}
				}
			}
			return null;
		}
		
		private function findServiceClass(factory:IAdapterFactory,className:String):Class{
			if(className == null){
				return null;
			}
			var array:Array = factory.getAdapterList();
			for each(var value:Object in array)
			{
				if(value is Class && getQualifiedClassName(value) == className){
					return value as Class;
				}
			}
			return null;
		}
		
		public function registerAdapters(factory:IAdapterFactory, adaptable:Class = null):void
		{
			KERNEL.registerService(factory,adaptable);
		}
		
		public function unregisterAdapters(factory:IAdapterFactory, adaptable:Class = null):void
		{
			//TODO:暂时不实现
		}
		
	}
}
	class Private{}